package com.example.demo.sf;


import java.util.ArrayList;
import java.util.List;

public class TestLiistNode {
    private static List< Integer> list = new ArrayList<>();
    public static void main(String[] args) {
        ListNode list1 = new ListNode(1);
        list1.next = new ListNode(2);
        list1.next.next = new ListNode(4);
        list1.next.next.next = new ListNode(5);
        list1.next.next.next.next = new ListNode(6);

        ListNode revert = revert(list1);
        System.out.println(revert);

        ListNode list2 = new ListNode(1);
        list2.next = new ListNode(3);
        list2.next.next = new ListNode(4);
//        head.next.next.next = new ListNode(3);
//        head.next.next.next.next = new ListNode(5);
//        System.out.println(list1);
//        ListNode listNode = removeNthFromEnd(head, 5);
//        ListNode listNode = deleteDuplicates(list1);
//        System.out.println(listNode);

//        System.out.println(mergeTwoLists( list1, list2));

    }

    public static ListNode deleteDuplicates(ListNode head) {
        ListNode left1 = head;
        ListNode left2 = head.next;
        while(left2 != null){
            if (left2.val == left1.val){
                left2 = left2.next;
            }else{
                left1.next = left2;
                left1 = left2;
                left2 = left2.next;
            }
        }
        left1.next = left2;
        return head;
    }

    public static ListNode removeNthFromEnd(ListNode head, int n) {
        if(null ==head){
            return head;
        }
        ListNode s = new ListNode(-100,head);
        ListNode heatTmp = s;
        int i=0;
        while(heatTmp.next != null){
            heatTmp = heatTmp.next;
            i++;
        }
        int removeIndex = i-n;
        ListNode cru = getNode(s,removeIndex);
        if(null != cru){
            cru.next = cru.next.next;
        }
        return s.next;
    }

    private static ListNode getNode(ListNode head,int index) {
        int i = 0;
        for (ListNode cur = head; cur != null; cur = cur.next,i++){
            if (i == index) {
                return cur;
            }
        }
        return null;
    }

    public ListNode mergeTwoLists2(ListNode list1, ListNode list2) {
        if(list1 == null){
            return list2;
        }
        if(list2 == null){
            return list1;
        }

        // 每次找出最小的节点，
        if (list1.val < list2.val){
            list1.next = mergeTwoLists2(list1.next,list2);
            return list1;
        }else{
            list2.next = mergeTwoLists2(list1,list2.next);
            return list2;

        }
    }

    public static ListNode revert(ListNode head) {
        ListNode n = null;
        while(head != null){
            ListNode next = head.next;
            head.next = n;
            n = head;
            head = next;
        }
        return n;
    }

}
